package com.ouc.pampas.controller;
import com.google.common.collect.Iterables;
import com.ouc.pampas.FileLoader;
import com.ouc.pampas.ThreadVars;
import com.ouc.pampas.FileLoaderHelper;
import com.ouc.pampas.MimeTypes;
import com.ouc.pampas.Splitters;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

@Component
public class AssetsHandler
{
  @Autowired
  private FileLoaderHelper fileLoaderHelper;
  
  public boolean handle(String path, HttpServletResponse response)
  {
    String lastPath = (String)Iterables.getLast(Splitters.SLASH.split(path));
    List<String> fileInfo = Splitters.DOT.splitToList(lastPath);
    if (fileInfo.size() == 1) {
      return false;
    }
    response.setContentType(MimeTypes.getType((String)Iterables.getLast(fileInfo)));
    String realPath = ThreadVars.getApp().getAssetsHome() + path;
    FileLoader.Resp resp = this.fileLoaderHelper.load(realPath);
    if (resp.isNotFound())
    {
      response.setStatus(HttpStatus.NOT_FOUND.value());
      return true;
    }
    response.setContentLength(resp.getContext().length);
    try
    {
      response.getOutputStream().write(resp.getContext());
    }
    catch (IOException e) {}
    return true;
  }
}
